package leetcode.editor.cn;

import java.util.*;

/**
 * Copyright (C) 2023 思创数码科技股份有限公司
 * <p/>
 * 版权所有
 * <p/>
 * 类名　　  : P502
 * 功能概要  :
 *
 * @Author : yangwk
 * @Date : 2024/1/8 22:32
 */
public class P502 {
    public static void main(String[] args) {
        int[] profits = new int[]{1, 2, 3};
        int[] capital = new int[]{0, 1, 1};
        System.out.println(findMaximizedCapital(2, 0, profits, capital));
    }

    static class Node {
        int profit;
        int capital;

        public int getProfit() {
            return profit;
        }

        public void setProfit(int profit) {
            this.profit = profit;
        }

        public int getCapital() {
            return capital;
        }

        public void setCapital(int capital) {
            this.capital = capital;
        }
    }

    public static int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
        List<Node> queue = new ArrayList<>();
        for (int i = 0; i < profits.length; i++) {
            int profit = profits[i];
            int capita = capital[i];
            Node node = new Node();
            node.setCapital(capita);
            node.setProfit(profit);
            queue.add(node);
        }
        queue.sort((o1, o2) ->  o1.getProfit() - o2.getProfit()==0? o1.getCapital() - o2.getCapital()
                : o1.getProfit() - o2.getProfit());
        int index = queue.size() - 1;
        while (!queue.isEmpty() && k > 0) {
            Node node = queue.get(index);
            if (node.getCapital() <= w) {
                queue.remove(index);
                k--;
                w += node.getProfit();
                index = queue.size() - 1;
            } else {
                index--;
            }
            if (index == -1) {
                break;
            }
        }
        return w;
    }

}
